<?php
date_default_timezone_set("Asia/Chongqing");
require 'Class/autoload.php';
require_once('Class/UpYun/vendor/autoload.php');
use Upyun\Upyun;
use Upyun\Config;

session_start();

//请求token
if(I('type','post') == 'token'){
	echo $token = md5(time()).md5(rand());
	$_SESSION[I('name','post')]= $token;
	exit;
}

//验证token
if(!@I('token','post') || @I('token','post') != @$_SESSION[I('type','post')]){
	echo 10001;
	Void_Token();
}




switch(I('type','post')){
	default :
		echo 'detault';
	break;





	case 'record_get_list':
		$pnow = @$_POST['pnow']?:1;
		if(@$_COOKIE['openid']){
			$openid = $_COOKIE['openid'];
			$pdo = MyPdo::init();
			$limit = 2;
			$limit_start = ($pnow-1)*$limit;
			$sql = "select * from car_move_order where openid1 = ? || openid2 = ? order by id desc limit {$limit_start},{$limit}";
			$res = $pdo->dql($sql,array($openid,$openid));
			if($res){
				$max_page = $pnow + 1;
			}else{
				$max_page = $pnow;
			}
			if($res){
				$sql2 = "select count(*) as count from car_move_order where openid1 = ? || openid2 = ?";
				$res2 = $pdo->dql($sql2,array($openid,$openid),1);
				$count = $res2['count'];
				if($count > 0){
					$max_page = ceil($count / $limit);
					Merge_Or_Make_Cache($res,'',array('pnow'=>$pnow,'max_page'=>$max_page));
					Void_Token();
				}
			}
			Merge_Or_Make_Cache($res,'',array('pnow'=>1,'max_page'=>1));
		}else{
			echo 'err';
		}
	break;






	case 'get_user_login_info':
		if(@$_SESSION['user_info']){
			echo $_SESSION['user_info'];
		}else{
			echo 'err';
		}
	break;




	//车牌误绑申请记录列表
	case 'complain_get_info_list':
		$openid = @$_COOKIE['openid'];
		$pnow = @$_POST['pnow'];
		//echo $pnow ;exit;
		if($openid){
			$limit = 3;		//每页显示条数
			$limit_start = ($pnow-1)*$limit;
			$pdo = MyPdo::init();
			$sql = "select number,info,ctime,stat,backinfo from car_move_complain where openid = ? order by id desc  limit {$limit_start},{$limit}";
			$res = $pdo->dql($sql,array($openid));
			$cache_path = 'Cache/Complain/'.$openid.$pnow;	//缓存数据

			//获取总页数
			$count_name = 'pnum_'.$openid;
			if(!S($count_name)){
				$sql2 = "select count(openid) as count from car_move_complain where openid = ?";
				$res2 = $pdo->dql($sql2,array($openid),1);
				$pnum = ceil($res2['count'] / $limit);
				S($count_name,$pnum);
			}else{
				$pnum =S($count_name);
			}
			Merge_Or_Make_Cache($res,$cache_path,array('pnow'=>$pnow,'max_page'=>$pnum));
		}else{
			echo 'err';
		}

	break;





	//提交车牌误绑申诉
	case 'complain_submit':
		$limit_size = 1024*500;	//限制图片大小
		$openid = ChangeChar($_COOKIE['openid']);
		$number = I('number','post');
		$info = I('info','post');
		$time = time();
		$pdo = MyPdo::init();
		$sql = 'select openid from car_move_complain where openid=? and number=? and stat=1';
		$res = $pdo->dql($sql,array($openid,$number),1);
		if(!$res){
			if(@$_FILES['img1'] && @$_FILES['img1']['size'] > 0 && @$_FILES['img1']['size'] < $limit_size	&& @$_FILES['img2'] && @$_FILES['img2']['size'] > 0 && @$_FILES['img2']['size'] < $limit_size){
				if($number && $info && $openid){
					$serviceConfig = new Config($config['upyun_bucketname'],$config['upyun_username'],$config['upyun_password']);
					$up = new Upyun($serviceConfig);
					$path = '/car_move/'.date('YmdHis').ceil(rand()*1000000).'.jpg';	//拼接文件名
					$res_img1 = $up->write($path,file_get_contents($_FILES['img1']['tmp_name']));
					if($res_img1['x-upyun-height']>0){
						$img1_path = $config['upyun_src'].$path;
						$path = '/car_move/'.date('YmdHis').ceil(rand()*1000000).'.jpg';	//拼接文件名
						$res_img2 = $up->write($path,file_get_contents($_FILES['img2']['tmp_name']));
						if($res_img1['x-upyun-height']>0){
							$img2_path = $config['upyun_src'].$path;
							$sql2 = "insert into car_move_complain values(null,?,?,?,?,?,1,'',$time)";
							$res2 = $pdo->dml($sql2,array($openid,$number,$info,$img1_path,$img2_path));
							if($res2){
								echo 'ok';
								$count_name = 'pnum_'.$openid;
								S($count_name,'');
								$cache_dir = 'Cache/Complain';
								DelDirs($cache_dir);	//删除缓存文件s
								//发送公众号模板到微信通知 
								$formwork =array(
									'touser'=>'omTFa02CiCTgB5FqQ4cHDcI7txXA',	//9201
									//'touser'=>'omTFa0-BG8RpFFRgZYTojLGCEWVk',	//不老松
									//'template_id'=>'JRkXQcpMYreNuxQ3wTFOXCniQ9htDeDoo1e1Kw0r9oQ',	//挪车模板id
									'template_id'=>'Zn876eGea44kerfyxRAoY83Ve2ub3bt7T_SULmPexE8',	//挪车模板id
									'data'=>array(	//推送模板中对应的数据
										'first'=>array('value'=>'有用户提交车牌误绑申请，请尽快处理!','color'=>'#ff0000'),
										'keyword1'=>array('value'=>'车牌误绑申请','color'=>'#0000ff'),
										'keyword2'=>array('value'=>date('Y-m-d H:i:s'),'color'=>'#0000ff'),
										'remark'=>array('value'=>'申诉车牌：'.$number,'color'=>'#173177')
									)
								);
								$res = sent_template_msg($formwork);
							}else{	
								echo 'err7';	//插入数据库失败
							}
						}else{
							echo 'err6';	//img2图片上传异常
						}
					}else{
						echo 'err5';	//img1图片上传异常
					}
				}else{
					echo 'err';		//缺少参数
				}
			}else{
				echo 'err3';	//缺少图片或图片大小超限
			}
		}else{
			echo 'err2';	//车牌申诉正在处理中,不要重复申诉	
		}

	break;




//地222222

	//向车牌对应用户发送模板消息
	case 'send_template_msg':
		$self_openid = @$_COOKIE['openid'];
		if($self_openid){
			$number = I('number','post');
			if($number){
				$openid = Get_Car_To_Openid($number);
				if($openid){
					//判断自己不能给自己发
					if($self_openid != $openid){
						$today_stamp = GetDateYmd('-0 day');	//获取当天零时时间戳
						$before_time = time() - 600;		//十分钟内不得再次发信息
						$pdo = MyPdo::init();
						$sql2 = 'select id from car_move_order where openid1=? and openid2=? and number=? and ctime > ?';
						$res2 = $pdo->dql($sql2,array($self_openid,$openid,$number,$before_time));
						//if(!$res2){
							$formwork =array(
								'touser'=>$openid,
								'template_id'=>'JRkXQcpMYreNuxQ3wTFOXCniQ9htDeDoo1e1Kw0r9oQ',	//挪车模板id
								'data'=>array(	//推送模板中对应的数据
									'first'=>array('value'=>'尊敬的用户您好，您有一条挪车请求。请尽快处理!','color'=>'#ff0000'),
									'keyword1'=>array('value'=>'挪车通知','color'=>'#0000ff'),
									'keyword2'=>array('value'=>$number,'color'=>'#0000ff'),
									'keyword3'=>array('value'=>date('Y-m-d H:i:s'),'color'=>'#0000ff'),
									'remark'=>array('value'=>'感谢您使用前行微信挪车服务！祝您生活愉快！','color'=>'#173177')
								)
							);
							$res = sent_template_msg($formwork);
							//var_dump($res);
							$p = '/"errcode":0,"errmsg":"ok"/';
							if(preg_match($p, $res)){
								$sql = 'insert car_move_order values(null,?,?,?,?,1)';
								$res = $pdo->dml($sql,array(time(),$self_openid,$openid,$number));
								if($res){
									echo 'ok';
								}else{
									echo 'err2';	//信息以推送，但记录失败
								}
							}else{
								echo 'err';	//信息推送失败
							}
						//}else{
						//	echo 'err6';	//十分钟内不能多次发送							
						//}
					}else{
						echo 'err3';	//不能给自己发信息
					}
				}else{
					echo 'err7';	//该车牌还没未注册
				}
			}else{
				echo 'err5';	//缺少车牌信息
			}
		}else{
			echo 'err4';	//用户未登陆
		}

	break;







	//用户添加绑定新车牌
	case 'band_car_number':
		$openid = I('openid','post');
		$number = strtoupper(I('number','post'));
		if($openid || $number){
			$pdo = MyPdo::init();
			$sql = 'select number from car_move_number where openid = ? || number = ?';
			$res = $pdo->dql($sql,array($openid,$number));
			if(!$res || count($res) < 5){
				if($res){
					//dump($res,1);
					foreach($res as $v){
						if($v['number'] == $number){
							echo 'err3';
							Void_Token();
						}
					}
				}
				$sql2 = 'insert into car_move_number values(null,?,?)';
				$res2 = $pdo->dml($sql2,array($openid,$number));
				if($res2){
					echo 'ok';
					$cache_name = 'Cache/UserBindCarList/'.$openid;
					del_file($cache_name);	//删除缓存文件
				}else{
					echo 'err2';	//绑定出现异常
				}
			}else{
				echo 'err1';	//车牌以存在或绑定个数超过5个
			}
		}else{
			echo 'err';	//缺少必要参数
		}
	break;



	//获取当前用户绑定的车牌列表
	case 'get_bind_car_list':
		$openid = I('openid','post');
		if(!$openid){
			echo 'err';
			Void_Token();
		}
		$pdo = MyPdo::init();
		$sql = 'select number from car_move_number where openid = ?';
		$res = $pdo->dql($sql,array($openid));
		$caceh_name = 'Cache/UserBindCarList/'.$openid;
		Merge_Or_Make_Cache($res,$caceh_name,array());
	break;




	//删除解绑已绑定车牌
	case 'del_bind_number':
		$openid = I('openid','post');
		$number = I('number','post');
		if($openid && $number){
			$pdo = MyPdo::init();
			$sql = 'delete from car_move_number where openid = ? and number = ?';
			$res = $pdo->dml($sql,array($openid,$number));
			if($res){
				echo 'ok';
				$cache_name = 'Cache/UserBindCarList/'.$openid;
				del_file($cache_name);	//删除缓存文件
			}else{
				echo 'err';
			}
		}
	break;




}



/*
	### 尝试删除指定文件(如果文件存在则删除)
	参一：文件路径
	return：无
*/
function del_file($fname){
	if(file_exists($fname)){
		unlink($fname);
	}
}


Void_Token();

//作废token
function Void_Token(){
	$_SESSION[I('type','post')] = md5(rand());
	exit;
}




/*
	### 通过车牌获取对应用户openid
	参一：车牌号
	return：匹配成功返回用户openid,失败返回false
*/
function Get_Car_To_Openid($number){
	$pdo = MyPdo::init();
	$sql = 'select openid from car_move_number where number=?';
	$res = $pdo->dql($sql,array($number),1);
	if($res){
		return $res['openid'];;
	}else{
		return false;
	}
}